package com.ysbt.ysbtapplicationcontext;

import com.ysbt.bean.Monster;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class YsbtApplicationContext {
    private ConcurrentHashMap singletonObject = new ConcurrentHashMap<>();
    public YsbtApplicationContext(String xmlPath) throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        SAXReader saxReader = new SAXReader();
        String pathClassPath = this.getClass().getResource("/").getPath();
        Document read = saxReader.read(pathClassPath + xmlPath);
        Element rootElement = read.getRootElement();
        Element bean = (Element)rootElement.elements().get(0);
        String id = bean.attributeValue("id");
        String aClass = bean.attributeValue("class");
        List<Element> property = bean.elements("property");
        Integer monsterId = Integer.parseInt(property.get(0).attributeValue("value"));
        String name = property.get(1).attributeValue("value");
        String skill = property.get(2).attributeValue("value");
        Class aClass1 = Class.forName(aClass);
        Monster monster = (Monster) aClass1.newInstance();
        monster.setId(monsterId);
        monster.setName(name);
        monster.setSkill(skill);
        singletonObject.put(id,monster);
    }
    public Object getBean(String id){
        return singletonObject.get(id);
    }
}
